<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { userUpdateInfoService } from '@/api/user'
import { useuserStore } from '@/stores'
import { ref } from 'vue'
const form = ref()
const {
  userInfo: { id, nickname, username, email },
  setuserInfo
} = useuserStore()
const formData = ref({
  id,
  username, // 默认登录名称
  nickname,
  email
})

const formRules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { pattern: /^\S{2,10}$/, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ]
}

const submitForm = async () => {
  const validate = await form.value.validate()
  if (validate) {
    await userUpdateInfoService(formData.value)
    await setuserInfo()
    ElMessage.success('提交成功')
  }
}
</script>
<template>
  <PageContainer>
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="demo-form"
      style="width: 50%"
    >
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="formData.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交修改</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
